package com.li.jiang.utils.role;
import cn.hutool.core.collection.CollectionUtil;
import com.li.jiang.Exception.AuthException;
import com.li.jiang.obj.dto.UserLoginData;
import com.li.jiang.utils.localThread.UserThreadLocal;
import com.li.jiang.utils.redis.RedisUtil;
import com.li.jiang.utils.token.TokenUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 **/
@Component
@Aspect
public class RoleAspect {
    @Autowired
    private RedisUtil redisUtil;
    @Pointcut
    public void pointCut(){

    }
    @Before("execution(* com.li.jiang.controller.*Controller.*(..))")
    public void before(JoinPoint joinPoint){
        System.out.println("执行前==================");
        MethodSignature signature= (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        System.out.println(method.getName());
        // 通过方法获取注解
        RequireRoles annotation = method.getAnnotation(RequireRoles.class);
        if (annotation!=null){
            //获取本地线程中的token key
            String localToken = UserThreadLocal.getToken();
            //获取redis中的token value
            String token = (String) redisUtil.get(localToken);
            if (token!=null){
                UserLoginData redisToken = TokenUtil.parseTokenData(token);
                Long redisRid = redisToken.getRid();
                List<Long> result = Arrays.stream(annotation.role()).map(Role::getRid).filter(value-> Objects.equals(redisRid, value)).collect(Collectors.toList());
                System.out.println("验证权限值:"+redisRid);
                System.out.println("方法权限数组："+ Arrays.toString(annotation.role()));
                System.out.println("比较结果:"+result);
                if (CollectionUtil.isEmpty(result)){
                    //grade值不匹配
                    throw new AuthException("没有权限");
                }
            }else{
                throw new AuthException("没有权限");

            }

        }
    }
}
